SimpleFetch = {
	requests		: 	{}
}

SimpleFetch.FetchAndEval = function (url) {
	var xro = SimpleFetch.BuildRequest(url);
	if (xro) {
		xro.eventRequestRecieved = SIMPLEFETCH_HANDLEEVALRETURN;
		xro.Open();
	}
}

SimpleFetch.BuildRequest = function (url) {
	var obj = SimpleFetch._getRequestObject();
	if (obj) {
		obj.requestedURL = url;
		
		obj.Open = SIMPLEFETCH_OPENCONNECTION;
			
		//event handlers
	 	obj.eventSocketOpened		=	function(){}
		obj.eventRequestSent		=	function(){}
		obj.eventRequestIncomming	=	function(){}
		obj.eventRequestRecieved	=	function(){}
		obj.eventRequestError		=	function(){}
		
		//SimpleFetch.requests[obj.requestedURL] = obj;
	}
	return obj;
}

SimpleFetch._getRequestObject = function () {
	var req;
	if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (req) {
		//req.onreadystatechange = SIMPLEFETCH_READYSTATECHANGE;
		req.onreadystatechange = function () {
			switch (req.readyState) {
				// usually, these steps happen too fast to see
				case 1: //Request: Open (send not called)
					req.eventSocketOpened();
					break;
				case 2: //Request: Sent (send called)
					req.eventRequestSent();
					break;
				case 3: //Request: Receiving (some content received)
					req.eventRequestIncomming();
					break;
				// The only case we usually care about is 4 (Complete)
				case 4:
					if (req.status == 200) { // OK response
						req.eventRequestRecieved();
					} else {
						req.eventRequestError();
					}
					break;
			}
		}
		return req;
	} else return null;
}

function SIMPLEFETCH_HANDLEEVALRETURN () {
	if (this.getResponseHeader("Content-Type") == "application/x-javascript") eval(this.responseText);
	else alert(this.responseText);
}

function SIMPLEFETCH_OPENCONNECTION () {
	try {
		this.open("GET", this.requestedURL, true);
		this.send('');
	} catch (e) {
		alert(e);
	}
}
